package com.tiancheng.trade.order.feign;

import com.tiancheng.trade.commom.web.http.PlatformRequest;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.exception.error.BusinessErrorInfoEnum;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.order.bo.CouponBO;
import com.tiancheng.trade.order.enums.CouponStatusEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 优惠券系统服务调用
 *
 * @author kellen
 * @date 2024/3/5
 */
@Component
@Slf4j
public class CouponSystemService {

    @Value(value = "${system.coupon.domain}")
    private String couponDomain;
    @Resource
    private PlatformRequest platformRequest;

    /**
     * 获取优惠券信息
     *
     * @param couponBO
     * @return
     */
    public CouponBO get(CouponBO couponBO) {
        Map<String, Object> params = new HashMap<>();
        params.put("uid", couponBO.getUid());
        params.put("code", couponBO.getCouponCode());
        try {
            Result result = platformRequest.jsonPostRequest(couponDomain + "/api/external/getCouponList", null,
                    params, this.getTokenHeader());
            log.error("查询优惠券返回:{}", result.toString());
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
            List<Map<String, Object>> unusedCoupons = (List<Map<String, Object>>) dataMap.get("unusedList");
            if (unusedCoupons.size() > 0) {
                couponBO.setCouponName(unusedCoupons.get(0).get("name").toString());
                couponBO.setCouponType(unusedCoupons.get(0).get("type").toString());
                couponBO.setDiscount(Integer.valueOf(unusedCoupons.get(0).get("money").toString()));
                couponBO.setRawInfo(unusedCoupons.get(0).get("remark").toString());
                couponBO.setCouponStatus(unusedCoupons.get(0).get("status").toString());
            }
        } catch (Exception e) {
            log.error("查询优惠券信息失败:code:{},msg:{}", couponBO.getCouponCode(),e.getMessage());
        }
        return couponBO;
    }

    /**
     * 锁定优惠券，状态(1 未绑定 2 绑定 3 锁定 4核销 5 作废 6过期)
     *
     * @param couponBO
     * @return
     */
    public CouponBO lock(CouponBO couponBO) {
        Map<String, Object> params = new HashMap<>();
        params.put("couponId", couponBO.getCouponCode());
        params.put("uid", couponBO.getUid());
        //params.put("orderNo", couponBO.getSubOrderId() != null ? couponBO.getSubOrderId() : couponBO.getOrderId());
        params.put("sceneId", Integer.valueOf(couponBO.getDiscountSource()));
        params.put("orderMoney", couponBO.getAmount());
        params.put("productId", couponBO.getProductCode());

        try {
            log.info("锁定优惠券请求参数："+params);
            Result result = platformRequest.jsonPostRequest(couponDomain + "/api/lockCoupon", null,
                    params, this.getTokenHeader());
            log.info("锁定优惠券结果："+result);
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
            couponBO.setCouponName(dataMap.get("name").toString());
            couponBO.setDiscount(Integer.valueOf(dataMap.get("disCountAmount").toString()));
            couponBO.setCouponStatus(CouponStatusEnum.lock.getCode());
        } catch (Exception e) {
            log.error("锁定优惠券失败:code:" + couponBO.getCouponCode());
            BusinessErrorInfoEnum.ORDER_CREATE_COUPON_LOCK.assertFail();
        }
        return couponBO;
    }

    /**
     * 解锁优惠券
     *
     * @param couponBO
     * @return
     */
    public CouponBO unlock(CouponBO couponBO) {
        Map<String, Object> params = new HashMap<>();
        params.put("uid", couponBO.getUid());
        params.put("couponId", couponBO.getCouponCode());
        //params.put("orderNo", couponBO.getSubOrderId() != null ? couponBO.getSubOrderId() : couponBO.getOrderId());
        try {
            log.info("解锁优惠券请求参数："+params);
            Result result = platformRequest.jsonPostRequest(couponDomain + "/api/unLockCoupon", null,
                    params, this.getTokenHeader());
            log.info("解锁优惠券结果："+result);
            couponBO.setCouponStatus(CouponStatusEnum.no_bind.getCode());
        } catch (Exception e) {
            log.error("解锁优惠券失败:code:" + couponBO.getCouponCode());
            BusinessErrorInfoEnum.ORDER_COUPON_UNLOCK.assertFail();
        }
        return couponBO;
    }

    /**
     * 核销优惠券
     *
     * @param couponBO
     * @return
     */
    public CouponBO writeOff(CouponBO couponBO) {
        Map<String, Object> params = new HashMap<>();
        params.put("couponId", couponBO.getCouponCode());
        params.put("uid", couponBO.getUid());
        params.put("orderId", couponBO.getOrderId());
        log.info("核销优惠券请求参数："+params);
        try {
            Result result = platformRequest.jsonPostRequest(couponDomain + "/api/writeOffCoupon", null,
                    params,  this.getTokenHeader());
            log.info("核销优惠券结果："+result);
            couponBO.setCouponStatus(CouponStatusEnum.verification.getCode());
        } catch (Exception e) {
            log.error("核销优惠券失败:code:" + couponBO.getCouponCode());
        }
        return couponBO;
    }

    /**
     * 退还优惠券
     *
     * @param couponBO
     * @return
     */
    public CouponBO returnCoupon(CouponBO couponBO) {
        Map<String, Object> params = new HashMap<>();
        params.put("couponId", couponBO.getCouponCode());
        params.put("uid", couponBO.getUid());
        log.info("退还优惠券请求参数："+params);
        try {
            Result result = platformRequest.jsonPostRequest(couponDomain + "/api/returnCoupon", null,
                    params, this.getTokenHeader());
            log.info("退还优惠券结果："+result);
            couponBO.setCouponStatus(CouponStatusEnum.no_bind.getCode());
        } catch (Exception e) {
            log.error("退还优惠券失败:code:" + couponBO.getCouponCode());
        }
        return couponBO;
    }


    /**
     * 获取优惠券服务的token
     *
     * @return
     * @throws Exception
     */
    private Header getTokenHeader() throws Exception {
        String token = platformRequest.getAccessToken();
        return new BasicHeader("token", token);
    }
}
